import axios from 'axios'
import { getToken, removeToken } from './utils'

// 创建实例
const instance = axios.create({
  baseURL: import.meta.env.VITE_BASE_API,
  timeout: 60000,
  timeoutErrorMessage: '请求超时，请稍后再试',
  withCredentials: true,
});

// 请求拦截器
instance.interceptors.request.use(
  config => {
    const token = getToken();
    if (token) {
      config.headers.Authorization = token
    }
    if (import.meta.env.VITE_MOCK == 'true') {
      config.baseURL = import.meta.env.VITE_MOCK_API_URL;
    } else {
      config.baseURL = import.meta.env.VITE_BASE_API;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
)

// 响应拦截器
instance.interceptors.response.use(
  response => {
    const data = response.data
    if (data.code == 401 || data.status == 401) {
      removeToken();
      window.location = '/login';
      return Promise.reject(response);
    }
    return response;
  },
  error => {
    if (error.status == 401) {
      removeToken();
      window.location = '/login';
    }
    return Promise.reject(error.message)
  }
)

export default {
  get(url, params, options) {
    return instance.get(url, { params, ...options });
  },
  post(url, params, options) {
    return instance.post(url, params, options);
  },
  downloadFile(url, data, fileName = 'fileName.xlsx') {
    instance({
      url,
      data,
      method: 'post',
      responseType: 'blob'
    }).then(response => {
      const blob = new Blob([response.data], {
        type: response.data.type
      })
      const name = (response.headers['file-name']) || fileName
      const link = document.createElement('a')
      link.download = decodeURIComponent(name)
      link.href = URL.createObjectURL(blob)
      document.body.append(link)
      link.click()
      document.body.removeChild(link)
      window.URL.revokeObjectURL(link.href)
    })
  },
  isCancel(value){
    return axios.isCancel(value);
  }
}
